<template>
  <div class="service-container">
    <el-card class="table-card">
      <template #header>
        <div class="table-header">
          <h3>通知管理</h3>
          <div class="search-toggle-area">
            <el-button class="search-toggle-button" @click="toggleSearchBar">
              <el-icon><Search /></el-icon>
            </el-button>
            <el-form :inline="true" :model="searchForm" class="search-form" :class="{'is-hidden': !showSearchBar}" ref="queryForm">
              <el-form-item label="类型">
                <el-select v-model="selectedType" placeholder="全部类型" clearable style="width: 160px;">
                  <el-option label="园区公告" value="园区公告"></el-option>
                  <el-option label="新闻资讯" value="新闻资讯"></el-option>
                  <el-option label="审批提醒" value="审批提醒"></el-option>
                  <el-option label="业务提醒" value="业务提醒"></el-option>
                  <el-option label="合同提醒" value="合同提醒"></el-option>
                  <el-option label="缴费提醒" value="缴费提醒"></el-option>
                  <el-option label="活动推广" value="活动推广"></el-option>
                  <el-option label="系统通知" value="系统通知"></el-option>
                </el-select>
              </el-form-item>
              <el-form-item label="标题">
                <el-input
                  v-model="searchQuery"
                  placeholder="请输入通知标题"
                  style="width: 220px;"
                  clearable
                  @clear="handleSearch"
                ></el-input>
              </el-form-item>
              <el-form-item>
                <el-button type="primary" @click="handleSearch">查询</el-button>
                <el-button @click="resetSearch">重置</el-button>
              </el-form-item>
            </el-form>
          </div>
        </div>
      </template>

      <el-table 
        :data="tableData" 
        v-loading="loading" 
        border
        stripe
        :header-cell-style="{background:'#f5f7fa', color:'#606266'}"
      >
        <el-table-column prop="title" label="标题" width="290" show-overflow-tooltip></el-table-column>
        <el-table-column prop="message_type" label="类型" width="120" align="center"></el-table-column>
        <el-table-column prop="publish_time" label="发布时间" width="200" align="center"></el-table-column>
        <el-table-column prop="valid_from" label="有效期开始" width="200" align="center"></el-table-column>
        <el-table-column prop="valid_until" label="有效期结束" width="200" align="center"></el-table-column>
        <el-table-column prop="read_count" label="阅读量" width="80" align="center"></el-table-column>
        <el-table-column label="操作" fixed="right" width="120" align="center">
          <template #default="scope">
            <el-button size="small" type="primary" link @click="handleView(scope.row.id)">查看</el-button>
          </template>
        </el-table-column>
      </el-table>

      <el-empty v-if="tableData.length === 0 && !loading" description="暂无通知数据" class="empty-data-placeholder"></el-empty>

      <div class="pagination-container">
        <el-pagination 
          :current-page="pagination.page"
          :page-size="pagination.size"
          :total="pagination.total"
          @current-change="handlePageChange"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
        ></el-pagination>
      </div>
    </el-card>

    <!-- 消息详情对话框 -->
    <el-dialog
      v-model="detailDialogVisible"
      title="通知详情"
      width="700px"
      append-to-body
    >
      <div v-if="currentMessage" class="message-detail">
        <el-descriptions border :column="2">
          <el-descriptions-item label="标题" :span="2">{{ currentMessage.title }}</el-descriptions-item>
          <el-descriptions-item label="消息类型">{{ currentMessage.message_type }}</el-descriptions-item>
          <el-descriptions-item label="发布时间">{{ currentMessage.publish_time }}</el-descriptions-item>
          <el-descriptions-item label="有效期开始">{{ currentMessage.valid_from }}</el-descriptions-item>
          <el-descriptions-item label="有效期结束">{{ currentMessage.valid_until }}</el-descriptions-item>
          <el-descriptions-item label="阅读量">{{ currentMessage.read_count }}</el-descriptions-item>
          <el-descriptions-item label="发布人">{{ currentMessage.sender_name }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusTagType(currentMessage.broadcast_status)">
              {{ currentMessage.broadcast_status }}
            </el-tag>
          </el-descriptions-item>
        </el-descriptions>
        
        <div class="content-box">
          <h4>通知内容</h4>
          <div class="content" v-html="currentMessage.content"></div>
        </div>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="detailDialogVisible = false">关闭</el-button>
          
          <!-- 仅针对"待处理"状态的草稿消息显示编辑按钮 -->
          <el-button 
            v-if="currentMessage && currentMessage.broadcast_status === '待处理'"
            type="primary" 
            @click="handleEdit(currentMessage.id)">
            编辑草稿
          </el-button>
          
          <!-- 删除按钮始终可见 -->
          <el-popconfirm 
            title="确定删除此通知吗？" 
            @confirm="handleDelete(currentMessage.id)"
            width="220">
            <template #reference>
              <el-button type="danger">删除</el-button>
            </template>
          </el-popconfirm>

          <!-- 针对草稿状态显示发布按钮 -->
          <el-button 
            v-if="currentMessage && currentMessage.broadcast_status === '待处理'"
            type="success" 
            @click="handlePublish(currentMessage.id)">
            发布通知
          </el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { getNotificationList, deleteNotification, getNotificationDetail } from '@/api/notifications';
import { ElMessage } from 'element-plus';
import { Search } from '@element-plus/icons-vue'

const router = useRouter();
const selectedType = ref('');
const searchQuery = ref('');
const tableData = ref([]);
const loading = ref(true);
const detailDialogVisible = ref(false);
const currentMessage = ref(null);
const showSearchBar = ref(false);
const searchForm = reactive({});

const pagination = ref({
  page: 1,
  size: 10,
  total: 0,
});

// 切换搜索栏显示状态
const toggleSearchBar = () => {
  showSearchBar.value = !showSearchBar.value;
};

const fetchData = async () => {
  loading.value = true;
  try {
    const params = {
      page: pagination.value.page,
      size: pagination.value.size,
      message_type: selectedType.value,
      title: searchQuery.value,
      broadcast_status: '已发布', // 只获取已发布的通知，不包括草稿
    };
    const res = await getNotificationList(params);
    if (res.data && res.data.code === 200) {
        tableData.value = res.data.data.list;
        pagination.value.total = res.data.data.total;
    } else {
        ElMessage.error(res.data.message || '获取通知列表失败');
    }
  } catch (error) {
    console.error('Failed to fetch notification list:', error);
    ElMessage.error('获取通知列表失败');
  } finally {
    loading.value = false;
  }
};

const handleSizeChange = (size) => {
  pagination.value.size = size;
  fetchData();
};

const handleSearch = () => {
  pagination.value.page = 1;
  fetchData();
}

const resetSearch = () => {
  selectedType.value = '';
  searchQuery.value = '';
  pagination.value.page = 1;
  fetchData();
}

const handleView = async (id) => {
  try {
    loading.value = true;
    const res = await getNotificationDetail(id);
    if (res.data && res.data.code === 200) {
      currentMessage.value = res.data.data;
      detailDialogVisible.value = true;
    } else {
      ElMessage.error(res.data.message || '获取通知详情失败');
    }
  } catch (error) {
    console.error('获取消息详情失败:', error);
    ElMessage.error('获取消息详情失败');
  } finally {
    loading.value = false;
  }
};

const handlePageChange = (page) => {
  pagination.value.page = page;
  fetchData();
};

const handleEdit = (id) => {
  router.push({ name: 'NotificationEdit', params: { id } });
};

const handleDelete = async (id) => {
  try {
    await deleteNotification(id);
    ElMessage.success('删除成功');
    detailDialogVisible.value = false; // 关闭详情对话框
    fetchData(); // 刷新列表
  } catch (error) {
    ElMessage.error('删除失败');
  }
};

// 获取状态标签类型
const getStatusTagType = (status) => {
  if (status === '待处理') return 'warning';
  if (status === '已发布') return 'success';
  return 'info';
};

// 发布草稿通知
const handlePublish = async (id) => {
  try {
    // 此处需要添加发布通知的API调用
    ElMessage.info('发布功能尚未实现，请在后端API开发完成后继续');
    // 示例代码:
    // await publishNotification(id);
    // ElMessage.success('通知发布成功');
    // fetchData();
    // detailDialogVisible.value = false;
  } catch (error) {
    ElMessage.error('发布失败');
  }
};

onMounted(() => {
  fetchData();
});
</script>

<style scoped>
.service-container {
  padding: 20px;
  background-color: #f8f9fa;
  min-height: calc(100vh - 80px);
}

.table-card {
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0,0,0,0.05);
}

.table-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.table-header h3 {
  margin: 0;
  font-size: 18px;
  font-weight: 600;
}

/* 搜索区域 */
.search-toggle-area {
  display: flex;
  flex-direction: row;
  align-items: center;
}

.search-toggle-button {
  font-size: 20px;
  color: #606266;
  align-self: center;
  margin-right: 15px;
  transition: all 0.2s;
  cursor: pointer;
  width: 36px;
  height: 36px;
  display: flex;
  justify-content: center;
  align-items: center;
  border-radius: 50%;
  background-color: rgba(0, 0, 0, 0.03);
  border: 1px solid rgba(0, 0, 0, 0.05);
  z-index: 10;
  margin-bottom: 0;
}

.search-toggle-button:hover {
  color: #409eff;
  background-color: rgba(64, 158, 255, 0.1);
  border-color: rgba(64, 158, 255, 0.2);
}

.search-form {
  max-width: 1000px;
  width: auto;
  overflow: hidden;
  transition: max-width 0.4s ease-in-out, opacity 0.4s ease-in-out, background-color 0.4s ease-in-out, box-shadow 0.4s ease-in-out, padding 0.4s ease-in-out, margin-left 0.4s ease-in-out, height 0.4s ease-in-out, min-height 0.4s ease-in-out;
  opacity: 1;
  background-color: transparent;
  border-radius: 8px;
  padding: 0 20px;
  box-shadow: none;
  pointer-events: auto;
  margin-left: 15px;
  white-space: nowrap;
  height: 35px;
  min-height: 35px;
}

.search-form.is-hidden {
  max-width: 0;
  opacity: 0;
  padding: 0;
  margin-left: 0;
  height: 0;
  min-height: 0;
  background-color: transparent;
  box-shadow: none;
  pointer-events: none;
}

/* 调整搜索表单项的底部外边距 */
:deep(.search-form .el-form-item) {
  margin-bottom: 0;
  margin-right: 15px;
  display: inline-flex;
  align-items: center;
}

:deep(.search-form .el-form-item__label) {
  padding-right: 8px;
}

:deep(.table-card .el-card__header) {
  background-color: #f9fafc;
  padding: 15px 20px;
}

:deep(.table-card .el-card__body) {
  padding: 20px;
}

.pagination-container {
  margin-top: 25px;
  display: flex;
  justify-content: flex-end;
  padding: 12px 15px;
  background-color: #f9fbfd;
  border-radius: 10px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
}

.empty-data-placeholder {
  margin-top: 40px;
}

.message-detail {
  padding: 0 20px;
}

.content-box {
  margin-top: 20px;
  border: 1px solid #EBEEF5;
  border-radius: 4px;
  padding: 20px;
}

.content-box h4 {
  margin-top: 0;
  padding-bottom: 10px;
  border-bottom: 1px solid #EBEEF5;
}

.content {
  min-height: 200px;
  padding: 10px 0;
  white-space: pre-wrap;
  word-break: break-word;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 搜索框el-input优化 */
:deep(.el-input__inner) {
  border-color: #e0e5ed !important;
  transition: border-color 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-input__inner:focus) {
  border-color: rgba(64, 158, 255, 0.4) !important;
}

:deep(.el-input__inner::placeholder) {
  color: #aebccf;
}

/* 按钮el-button优化 */
:deep(.el-button--primary) {
  background-color: rgba(64, 158, 255, 0.1) !important;
  color: #606266 !important;
  border-color: rgba(64, 158, 255, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--primary:hover) {
  background-color: rgba(64, 158, 255, 0.15) !important;
  border-color: rgba(64, 158, 255, 0.3) !important;
}

/* Default Button */
:deep(.el-button--default) {
  background-color: #ffffff !important;
  color: #606266 !important;
  border-color: #dcdfe6 !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--default:hover) {
  background-color: #f7f9fa !important;
  border-color: #c8d3dd !important;
}

/* Success Button */
:deep(.el-button--success) {
  background-color: rgba(103, 194, 58, 0.1) !important;
  color: #67C23A !important;
  border-color: rgba(103, 194, 58, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--success:hover) {
  background-color: rgba(103, 194, 58, 0.15) !important;
  border-color: rgba(103, 194, 58, 0.3) !important;
}

/* Danger Button */
:deep(.el-button--danger) {
  background-color: rgba(245, 108, 108, 0.1) !important;
  color: #F56C6C !important;
  border-color: rgba(245, 108, 108, 0.2) !important;
  transition: all 0.2s cubic-bezier(0.645, 0.045, 0.355, 1);
  border-radius: 6px;
}

:deep(.el-button--danger:hover) {
  background-color: rgba(245, 108, 108, 0.15) !important;
  border-color: rgba(245, 108, 108, 0.3) !important;
}
</style> 